<?php
/**
 * Created by PhpStorm.
 * User: denh
 * Date: 16/5/17
 * Time: 下午2:17
 */
//我的爱贝个人信息--wym
class UserController extends BaseController {

    function __construct($m = DEFAULT_CONTROLLER, $a = DEFAULT_METHOD) {
        parent::__construct($m, $a);

        $this->redirectToWeixinForOpenid();
        if (!$this->openId()) {
            $this->errorPage('系统出错了[openID获取失败]');
        }

        $do_user = new Do用户();
        $do_user->set_openID($this->openId());
        if (!$do_user->where($do_user->data)->row()) {
            $this->errorPage('请先关注爱贝儿医公众号');
        }
        $this->do_user = $do_user;
    }

    //我的爱贝--手机号码认证
    function user_register() {
        if($this->do_user->get_密码()){
            $this->redirect('user','user_base');
        }

        $认证url = $this->url('user', 'user_base');
        require $this->template;
    }

    function user_register_post() {
        $tel = $this->request('tel','', true);
        $pwd = $this->request('pwd','', true);

        if (!Tools::checkPhone($tel)) {
            $this->jsonOutPut(-1, '手机号格式不正确');
        }

        $this->load_hprose(USER_CENTER_BASE_URL);
        $re_checkYzm = self::$hproseHttpClient->UserCenterController_checkCode($tel, $pwd);

        logger()->logInfo("校验验证码：$tel, $pwd".var_export($re_checkYzm, true));
        if (!$re_checkYzm->result) {
            $this->jsonOutPut(-1, '验证码不正确');
        }

        require_once ROOT_PATH . '/bs/bs.automation.php';

        $auto = new automation();
        $re_phone = $auto->get_area_by_phone($tel);
        if ($re_phone) {
            $this->do_user->set_province($re_phone['result']['province']);
            $this->do_user->set_city($re_phone['result']['city']);
        }

        #在用户中心注册手机号
        $re_interface = self::$hproseHttpClient->UserCenterController_wxSetPhone($tel, $this->openId(), $pwd);
        logger()->logInfo("UserCenterController_wxSetPhone". var_export($re_interface, true));
        if ($re_interface->code != 0) {
            $this->jsonOutPut(-1, $re_interface->msg);
        }

        require_once ROOT_PATH . '/bs/BsUserCenter.php';
        $userCenter = new BsUserCenter();
        $userCenter->writeSession($re_interface); #更新用户中心的session信息

        $this->do_user->set_telephone($tel);
        $this->do_user->set_密码($pwd);
        $this->do_user->set_telephone_time(date("Y-m-d H:i:s"));
        $re = $this->do_user->save();
        if (!$re) {
            $this->jsonOutPut(-1, '注册失败');
        }

        $re_1 = $this->doctor_auto_pass($tel);
        $re_2 = $this->doctor_auto_pass_from_app($re_interface);
        logger()->logInfo("re_1:".$re_1. "re_2". $re_2);

        if ($re_1 or $re_2) {
            $this->jsonOutPut(0, '', '2');
        } else {
            $this->jsonOutPut(0, '', '1');
        }
    }

    #直接通过医师审核
    private function doctor_auto_pass($phone) {

        $user_id = $this->do_user->get_id();
        $do = new DoDoctor_auto_pass();
        $do->set_phone($phone);
        $do->set_is_register('0');
        if (!$do->where($do->data)->row()) {
            return false;
        }

        $do医师 = new Do医师详情();
        $do医师->set_用户id($user_id);
        if ($do医师->where($do医师->data)->row()) {
            logger()->logInfo("===doctor_auto_pass：已经通过医师审核");
            return false;
        }

        self::$pdo->beginTransaction();
        $this->do_user->set_telephone($phone);
        $this->do_user->set_name($do->get_name());
        $this->do_user->set_认证(3);
        $re = $this->do_user->save();

        $do医师->set_name($do->get_name());
        $do医师->set_简介($do->get_description());
        $do医师->set_状态('通过');
        $do医师->set_专业领域($do->get_keshi());
        $do医师->set_医院($do->get_hospital());
        $do医师->set_职务($do->get_zhicheng());
        $do医师->set_资格证号($do->get_certificate_id());
        $re1 = $do医师->save();

        $do->set_is_register(1);
        $do->set_register_time(date("Y-m-d H:i:s"));
        $re2 = $do->save();

        if (!$re or !$re1 or !$re2) {
            self::$pdo->rollBack();
            logger()->logInfo("===doctor_auto_pass：数据库更新失败：$re: $re1: $re2");
            return false;
        } else {
            self::$pdo->commit();
        }

        $weixinNews = C信息中心::get实列根据公众号OpenId();
        $weixinNews->ff发送文本消息($this->config_msg(), $this->openId());
        return true;
    }

    /**
     * 获取app的用户资料
     * @param $re object 用户中心接口UserCenterController_wxSetPhone返回结果
     * @return bool
     */
    private function doctor_auto_pass_from_app($re) {
        logger()->logInfo("===call doctor_auto_pass_from_app");

        $user_id = $this->do_user->get_id();
        $do医师 = new Do医师详情();
        $do医师->set_用户id($user_id);
        if ($do医师->where($do医师->data)->row()) {
            logger()->logInfo("===doctor_auto_pass_from_app：已经通过医师审核");
            return false;
        }

        #未通过认证
        if ($re->result->account->status != '1') {
            return false;
        }

        self::$pdo->beginTransaction();
        $this->do_user->set_name($re->result->author->name);
        $this->do_user->set_认证(3);
        $re_user = $this->do_user->save();

        $do医师->set_name($re->result->author->name);
        $do医师->set_简介('');
        $do医师->set_状态('通过');
        $do医师->set_专业领域($re->result->author->sector);
        $do医师->set_医院($re->result->author->hospital);
        $do医师->set_职务($re->result->author->title);
        $do医师->set_资格证号('');
        $do医师->set_note('from app');
        $do医师->set_createTime(date("Y-m-d H:i:s"));
        $re_doctor = $do医师->save();

        if (!$re_user or !$re_doctor) {
            self::$pdo->rollBack();
            logger()->logInfo("===doctor_auto_pass：数据库更新失败：$re_user: $re_doctor");
            return false;
        } else {
            self::$pdo->commit();
        }

        $weixinNews = C信息中心::get实列根据公众号OpenId();
        $weixinNews->ff发送文本消息($this->config_msg(), $this->openId());
        return true;
    }

    function config_msg() {
        $url_conference = $this->url('meeting', 'index');
        $url_course = $this->url('course','index');
        $url_bingli = $this->url('case', 'index');
        $url_iread = $this->url('iread', 'index');

        $msg = "账户关联成功（已认证），欢迎您的加入！

最新学术会议：<a href='$url_conference'>【爱会议】</a>

儿科学习平台：<a href='$url_course'>【爱课堂】</a>

病例交流讨论：<a href='$url_bingli'>【爱病例】</a>

最新资讯分享：<a href='$url_iread'>【爱阅读】</a>

爱贝儿医——儿科医生的学习工作交流平台！";
        return $msg;
    }

    #发送验证码
    function user_register_send_checkCode() {
        $tel = $this->request('tel', '', true);

        #$content = $num. "仅本次有效，请勿转发或告知他人。";
        #Tools::send_text_messages($content, $tel);
        $this->load_hprose();
        $re = self::$hproseHttpClient->AccountController_sendCode($tel);
        logger()->logInfo("AccountController_sendCode: ". var_export($re, true)); ###
        $this->jsonOutPut(1,'手机号码可用');

    }

    function user_base(){
        if(!$this->do_user->get_密码()){
            $this->redirect('user','user_register');
        }
        $do_user = new Do用户();
        $do_doctor = new Do医师详情();
        $user_id = $this->do_user->get_id();
        $do_user->fields("a.头像 as 头像,a.密码 as 密码 ,a.认证 as 认证 ,b.*");
        $do_user->leftJoin($do_doctor, 'b', 'a.id = b.用户id');
        $do_user->where("a.id = " . $user_id);
        $myself_res = $do_user->row();


        $avatar = trim($myself_res->data['头像']);
        if (!$avatar) {
            $avatar = G_SITE_BASE . '/business/style/renxiang.png';
        }
        if (substr($avatar, 0, 4) != 'http') {
            $avatar = G_SITE_BASE . '/business/' . $avatar;

        }

        if($myself_res->data['照片']){
            $pic = $myself_res->data['照片'];
        }else{
            $pic = "business/style/user/style/inputtu.png";
        }

        $up_user_img = $this->url('user','up_user_img');
        $zhicheng = require ROOT_PATH . 'config/config.zhicheng.php';
        $keshi = require ROOT_PATH . 'config/config.keshi.php';
        $this->data['zhicheng'] = json_encode($zhicheng);
        $this->data['keshi'] = json_encode($keshi);
        $use_post_url = $this->url('user','user_base_post');
        require $this->template;
    }

    function user_base_post(){
        $name = $this->request('name', '', true);
        $职务 = $this->request('zhiwu');
        $医院 = $this->request('医院', '', true);
        $专业领域 = $this->request('专业领域', '',true);
        $简介 = $this->request('remark');
        $type = $this->request('type','',true);

        if($type!='医学生' && strlen($职务)==0 ){

         //$this->jsonOutPut('-1','zhiwu为必填字段');
        }

        $do_user = new Do用户();
        $do_doctor = new Do医师详情();

        $user_id = $this->do_user->get_id();
        $doc_state = '';
        $do_doctor->where('用户id = ' . $user_id)->row();
        $doc_id = $do_doctor->get_id();

        if ($doc_id) {
            $doc_state = $do_doctor->get_状态();
        }
        if (!$doc_id or $doc_state == '待完善') {
            $do_doctor->set_createTime(date("Y-m-d H:i:s", time()));
        }

        $do_doctor->set_name($name);
        $do_doctor->set_用户id($user_id);
        $do_doctor->set_医院($医院);
        $do_doctor->set_职务($职务);
        $do_doctor->set_专业领域($专业领域);
        $do_doctor->set_简介($简介);
        $do_doctor->set_资格证号($_POST['资格证号']);
        $state = $this->is_pass($this->do_user->get_superior(), $doc_state);
        $do_doctor->set_状态($state);
        $do_doctor->set_userType($type);

        if (!$do_doctor->get_openID()) {
            $do_doctor->set_openID($this->do_user->get_openID());
        }

        if ($state == '通过' and !$do_doctor->get_checkTime()) {
            $do_doctor->set_checkTime(date("Y-m-d H:i:s"));
        }
        $res_doctor = $do_doctor->save();

        if ($res_doctor) {

            if ($type == '医生') {
                $type_value = 0;
            } elseif ($type == '护士') {
                $type_value = 1;
            } elseif ($type == '医学生') {
                $type_value = 2;
            } else {
                $type_value = -1;
            }
            $this->load_hprose(USER_CENTER_BASE_URL);

            $userCenterToken = $this->get_UserCenterToken($this->do_user->get_openID());
            $re_interface = self::$hproseHttpClient->UserCenterController_setVerificationInfo(
                $userCenterToken,
                $name,
                $type_value,
                $医院,
                $专业领域,
                $职务
            );
            logger()->logInfo("UserCenterController_setVerificationInfo:".var_export($re_interface, true));###

            $do_user->set_id($user_id);
            $do_user->set_name($name);
            $do_user->set_description($简介);
            $do_user->set_更新缓存("是");
            if ($state == '通过') {
                $do_user->set_认证('3');
            }
            $res_user = $do_user->save();

            if ($res_user) {
                $do_user->fields('认证')->row($user_id);
                if ($do_user->get_认证() == 1 || $do_user->get_认证() == "") {

                    $this->successPage('您的认证信息已提交，我们将会在12小时内进行审核！');

                } else {
                    $re_quickAuth = self::$hproseHttpClient->UserCenterController_quickAuth($userCenterToken);
                    logger()->logInfo("UserCenterController_quickAuth:".var_export($re_quickAuth, true));###

                    $this->successPage("您认证通过！");
                }
            }
        } else {
            exit("<script>alert('提交失败');</script>");
        }
    }

    function is_pass($superior,$state) {
        $do_expert = new Do专家();
        $do_system = new DoSystem_config();
        $do_system->row('1');
        $expert = $do_expert->where('id = '.$superior)->row();

        if ($do_system->get_c_value() == 1 || !empty($expert->data) || $state == '通过') {
            return '通过';
        }
        return '待审核';
    }

    //用户基本信息，上传个人真实照片医师工作证
    function up_user_img(){
        $imageId = $this->request('imageId', '', true);
        $Tools = new Tools();
        $Token = $Tools->fh通过公众号id获取公众号Token信息(G_SERV_ID);

        $url2 = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $Token . "&media_id=" . $imageId;

        $dir = 'cache/text_img';
        $file_path = $dir . '/' . date("YmdHis", time()) . ".jpg";

        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $ret2 = $Tools->curl_get_page_新($url2);
        $c生成文件 = $Tools->f生成文件($file_path, $ret2);
        $pic_url = Tools::upload_qiniu_fromServer($file_path);
        unlink($file_path); logger()->logInfo("已删除临时文件" . $file_path);

        $this->load_hprose(USER_CENTER_BASE_URL);

        $userCenterToken = $this->get_UserCenterToken($this->do_user->get_openID());

        if ($_REQUEST['table'] == 'user_table') {
            $this->do_user->set_头像($pic_url);
            if ($this->do_user->save()) {
                $re_interface = self::$hproseHttpClient->UserCenterController_setBaseInfo($userCenterToken, $pic_url, null, null);
                logger()->logInfo("UserCenterController_setBaseInfo:".var_export($re_interface, true));
            }

        } else {
            $do_hospital = new Do医师详情();
            $do_hospital->set_id($_REQUEST['id']);
            $do_hospital->set_用户id($this->do_user->get_id());
            $do_hospital->set_照片($pic_url);
            if ($do_hospital->save()) {
                $re_interface = self::$hproseHttpClient->UserCenterController_setVerificationImg($userCenterToken, $pic_url);
                logger()->logInfo("UserCenterController_setVerificationImg:".var_export($re_interface, true));
            }
        }

       echo $pic_url;
    }

    //我的邀请好友--seller11Qrcodea
    function user_qrcode(){
        $do_admin = new Do后台管理员();
        $do_admin->set_公众号ID($_SESSION['vo用户数据']['公众号ID']);
        $share_content = $do_admin->where($do_admin->data)->row();

        $do_expand_file = new Do推广文章();
        $do_expand_file->set_是否显示('是');
        $do_expand_file->set_公众号ID($_SESSION['vo用户数据']['公众号ID']);
        $expend_list = $do_expand_file->where($do_expand_file->data)->rows();

        $parm = array('uid'=> $this->do_user->get_id());
        $my_qrcode_url = $this->url('user','user_myqrcode',$parm);
        require $this->template;
    }

    //我的推广二维码
    function user_myqrcode(){
        $uid = $_REQUEST['uid'];
        $file_id = $_REQUEST['wzid'];
        $do_user_expend = new Do用户推广表;
        $do_file_expend = new Do推广文章();
        $do_user = new Do用户();
        $do_doctor = new Do医师详情();
        
        $do_user_expend->set_用户id($uid);
        //用户推广
        $user_myqrcode = $do_user_expend->where($do_user_expend->data)->row();
        $do_file_expend->set_id($file_id);

        $do_user->leftJoin($do_doctor,'b','a.id = b.用户id');
        $myself = $do_user->fields('头像,description,密码,b.*')->where('a.id = '.$uid)->row();
        $user_id = $this->do_user->get_id();
        $ajax_share_expend = $this->url('user','apply_expend');
        require $this->template;
    }

    //重构，功能正常使用方法
    function apply_expend(){
       $user_id = $_REQUEST['user_id'];
        $openId=$this->openId();
        $bm=new CUI数据中心(Page::m卖家中心_账目,$openId);
        $c_user = new C用户($bm->vo信息中心);
        $qrcode_res = $c_user->f申请成为推广人($user_id);
        echo $qrcode_res;

    }

    function getHospitals(){
        $token = $_SESSION['app_token'];
        $name = $this->request('name', '', true);
        $this->load_hprose();
        $res = self::$hproseHttpClient->Setting_searchHospital($token, $name);
        logger()->logInfo(var_export($res, true));
        if($res->result){
            $this->jsonOutPut(0, '医院获取成功', $res->result);
        }else{
            $this->jsonOutPut(-1, '医院获取失败');
        }
    }

    function getUniversity(){
        $token = $_SESSION['app_token'];
        $name = $this->request('name');
        $this->load_hprose();
        $res = self::$hproseHttpClient->Setting_searchUniversity($token, $name);
        if($res->result){
            $this->jsonOutPut(0, '大学信息获取成功', $res->result);
        }else{
            $this->jsonOutPut(-1, '大学信息获取失败');
        }
    }

}